package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

//订单定时任务
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;
    //处理超时订单,每一分钟处理一次
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeOut(){
        //查找符合条件的订单,未支付状态，且下单时间<当前时间-15分钟
        LocalDateTime now = LocalDateTime.now();
        log.info("处理超时订单当前时间:{}",now);
        LocalDateTime time = now.plusMinutes(-15);//当前时间-15分钟
        List<Orders> orders = ordersMapper.getByStatusTime(Orders.PENDING_PAYMENT,time);
        //当订单不为空时，取消超时订单
        if(null != orders && orders.size() > 0){
            List<Orders> tem = new ArrayList<>();
            for (Orders order : orders){//获取每个订单
                Orders orders1 = new Orders();
                orders1.setId(order.getId());//设置订单id
                orders1.setStatus(Orders.CANCELLED);//设置订单状态为“已取消”
                orders1.setCancelTime(LocalDateTime.now());//订单取消时间
                //orders1.setCancelReason("用户超时未支付");//订单取消原因
                tem.add(orders1);
            }
            ordersMapper.updateBatch(tem);//批量更新
        }
    }

    //(每天凌晨1点)处理前一天已完成但订单状态还是派送中的订单
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDelivery(){
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime time = now.minusMinutes(-60);//前一天的晚上12点
        log.info("修改订单状态:派送中->已完成");
        //查找订单状态为派送中的订单
        List<Orders> orders = ordersMapper.getByStatusTime(Orders.DELIVERY_IN_PROGRESS, time);
        if(null != orders && orders.size() > 0){
            List<Orders> tem = new ArrayList<>();
            //遍历订单
            for (Orders order: orders){
                Orders orders1 = new Orders();
                orders1.setId(order.getId());//设置订单id
                orders1.setStatus(Orders.COMPLETED);//设置订单状态为已完成
                orders1.setDeliveryTime(LocalDateTime.now());//设置订单送达时间
                tem.add(orders1);
            }
            ordersMapper.updateBatch(tem);
        }
    }
}
